from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q, ProtectedError

from clazz.models import Clazz
from utils.customerutils import CustomerUtils
from utils.responsestatus import ResponseStatus
from utils import responsedata
from django.db import IntegrityError


# Create your views here.
#  搜索分页
def clazz_page(request):
    if request.method == 'POST':
        # {page:1,size:5，headteacher,class_room,class_state}
        form_data = CustomerUtils.get_request_data(request)
        condition = Q()
        # 动态条件
        if form_data.get('headteacher').strip():
            condition &= Q(headteacher__icontains=form_data['headteacher'])
        if form_data.get('class_room').strip():
            condition &= Q(class_room__icontains=form_data['class_room'])
        # active  0  1
        if form_data.get('class_state') != '':
            condition &= Q(class_state=form_data['class_state'])
        # 分页处理  total  tableData
        clazz_list = Clazz.objects.filter(condition).order_by('-id')
        # 获取分页对象
        paginator = Paginator(clazz_list, form_data.get('size', 5))
        # 获取数据总条数
        total = paginator.count
        # 当前页对象
        try:
            current_page = paginator.page(form_data.get('page', 1))
        except EmptyPage as e:
            current_page = paginator.page(1)
        # 当前页数据   [{},{},{}]
        table_data = current_page.object_list
        clazzs = []
        for clazz in table_data:
            clazzs.append({
                'id': clazz.id,
                'class_name': clazz.class_name,
                'class_room': clazz.class_room,
                'class_state': clazz.class_state,
                'class_start': clazz.class_start.strftime('%Y-%m-%d'),
                'student_number': clazz.student_number,
                'headteacher': clazz.headteacher

            })
        response = {
            'code': ResponseStatus.BUSINESS_SUCCESS,
            'data': {
                'total': total,
                'tableData': clazzs
            }
        }

        return CustomerUtils.response_json(response)


def clazz_state(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        Clazz.objects.filter(id=form_data.get('id')).update(class_state=form_data.get('state'))
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def clazz_one(request, id):
    clazz = Clazz.objects.filter(id=id).first()
    responsedata = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'clazz': {
                'id': clazz.id,
                'class_name': clazz.class_name,
                'class_room': clazz.class_room,
                'class_state': clazz.class_state,
                'class_start': clazz.class_start.strftime('%Y-%m-%d'),
                'student_number': clazz.student_number,
                'headteacher': clazz.headteacher
            }
        }
    }
    return CustomerUtils.response_json(responsedata)


def clazz_insert_edit(request):
    if request.method == 'POST':
        form_data = CustomerUtils.get_request_data(request)
        clazz_id = form_data.get('id')
        try:
            if clazz_id is not None:
                # 更新
                Clazz.objects.filter(id=clazz_id).update(**form_data)
            else:
                Clazz(**form_data).save()
        except IntegrityError as e:
            response = responsedata.BUSINESS_ERROR_DATA
            response['message'] = str(e)
            return CustomerUtils.response_json(response)
        else:
            return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)


def clazz_remove(request, id):
    try:
        Clazz.objects.filter(id=id).delete()
        return CustomerUtils.response_json(responsedata.BUSINESS_SUCCESS_DATA)
    except ProtectedError as e:
        response = {
            'code': ResponseStatus.BUSINESS_ERROR,
            'message': '班级被占用,不能删除!!!'
        }
        return CustomerUtils.response_json(response)


def clazz_list(request):
    clazz_list = Clazz.objects.all()
    clazzs = []
    for clazz in clazz_list:
        clazzs.append({
            'id': clazz.id,
            'class_name': clazz.class_name,
        })

    responsedata = {
        'code': ResponseStatus.BUSINESS_SUCCESS,
        'data': {
            'clazzList': clazzs
        }
    }
    return  CustomerUtils.response_json(responsedata)
